package com.fourforfo.fourmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fourforfo.common.to.SkuInfoAndAttrsTO;
import com.fourforfo.common.to.SkuStockTO;
import com.fourforfo.common.to.mq.OrderTO;
import com.fourforfo.common.to.mq.SeckillOrderTO;
import com.fourforfo.common.utils.R;
import com.fourforfo.fourmall.order.config.MyOrderMQConfig;
import com.fourforfo.fourmall.order.constant.OrderConstant;
import com.fourforfo.fourmall.order.constant.OrderStatusEnum;
import com.fourforfo.fourmall.order.entity.OrderItemEntity;
import com.fourforfo.fourmall.order.entity.PaymentInfoEntity;
import com.fourforfo.fourmall.order.feign.CartFeignService;
import com.fourforfo.fourmall.order.feign.MemberFeignService;
import com.fourforfo.fourmall.order.feign.ProductFeignService;
import com.fourforfo.fourmall.order.feign.WareFeignService;
import com.fourforfo.fourmall.order.service.OrderItemService;
import com.fourforfo.fourmall.order.to.OrderCreateTO;
import com.fourforfo.fourmall.order.to.SpuInfoTO;
import com.fourforfo.fourmall.order.to.WareSkuLockTO;
import com.fourforfo.fourmall.order.vo.*;
import com.fourforfo.fourmall.order.vo.alipay.PayAsyncVO;
import com.fourforfo.fourmall.order.vo.alipay.PayVO;
import com.xxl.sso.core.user.XxlSsoUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fourforfo.common.utils.PageUtils;
import com.fourforfo.common.utils.Query;

import com.fourforfo.fourmall.order.dao.OrderDao;
import com.fourforfo.fourmall.order.entity.OrderEntity;
import com.fourforfo.fourmall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    OrderItemService orderItemService;

    @Autowired
    PaymentInfoServiceImpl paymentInfoService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    ThreadPoolExecutor executor;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取订单确认页面所需的各种信息
     * @return
     */
    @Override
    public OrderConfirmVO confirmOrder(XxlSsoUser xxlSsoUser) {
        OrderConfirmVO orderConfirmVO = new OrderConfirmVO();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1、远程获取用户address
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberReceiveAddressVO> address = memberFeignService.getAddress(Long.parseLong(xxlSsoUser.getUserid()));
            orderConfirmVO.setAddress(address);
        }, executor);

        CompletableFuture<Void> getCartItemFuture = CompletableFuture.runAsync(() -> {
            //2. 远程获取当前用户的购物项信息
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<CartItemVO> cartItemVOS = cartFeignService.currentUserCartItems();
            orderConfirmVO.setCartItems(cartItemVOS);
        }).thenRun(()->{//List<SkuStockTO>
            List<CartItemVO> cartItemVOS = orderConfirmVO.getCartItems();
            List<Long> skuIds = cartItemVOS.stream().map(cartItemVO -> cartItemVO.getSkuId()).collect(Collectors.toList());
            R r = wareFeignService.listBySkus(skuIds);
            if(r.getCode()==0){
                List<SkuStockTO> skuStockTOS = r.getData(new TypeReference<List<SkuStockTO>>() {
                });
                if(skuStockTOS!=null){
                    Map<Long, Integer> collect = skuStockTOS.stream().collect(Collectors.toMap(SkuStockTO::getSkuId, SkuStockTO::getStock));
                    for (CartItemVO cartItemVO : cartItemVOS) {
                        cartItemVO.setHasStock(collect.get(cartItemVO.getSkuId())>0);
                    }
                }
            }

        });

        CompletableFuture.allOf(getAddressFuture,getCartItemFuture).join();

        //3.查询用户积分
        orderConfirmVO.setIntegration(xxlSsoUser.getIntegration());

        //4.orderConfirmVO是一个充血模型，可以根据cartItems自动计算总价格等信息

        //5.防重令牌实现接口的幂等性
        String token = UUID.randomUUID().toString().replace("-", "");
        orderConfirmVO.setOrderToken(token);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+xxlSsoUser.getUserid(),token, 30,TimeUnit.MINUTES);


        return orderConfirmVO;
    }

    /**
     * 下单
     *  创建订单、验证token令牌、验证价格、锁库存
     * @param submitVO
     * @param xxlUser
     * @return
     */

//    @GlobalTransactional
    @Transactional
    @Override
    public OrderSubmitResponseVO submitOrder(OrderSubmitVO submitVO, XxlSsoUser xxlUser) {
        OrderSubmitResponseVO orderSubmitResponseVO = new OrderSubmitResponseVO();
        //1.验证令牌，对比和删除必须保证原子性
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = submitVO.getOrderToken();
        String key = OrderConstant.USER_ORDER_TOKEN_PREFIX+xxlUser.getUserid();
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(luaScript, Long.class), Arrays.asList(key), orderToken);
        if(result == 1l){
            //等于1l表示删除成功
            //2. 创建订单,订单项等信息
            OrderCreateTO orderCreateTO = createOrder(submitVO,Long.valueOf(xxlUser.getUserid()));
            orderCreateTO.getOrderEntity().setMemberUsername(xxlUser.getUsername());//设置一下会员名字
            //3. 验价
            BigDecimal payAmount = orderCreateTO.getOrderEntity().getPayAmount();
            BigDecimal payPrice = submitVO.getPayPrice();
            if(payAmount.subtract(payPrice).abs().doubleValue()<0.01){
                //金额对比成功，由于两者精度不一致，所以只需要两个的值相差不大于0.01就判断两个相等
                //TODO 4.保存订单
                saveOrder(orderCreateTO);
                //TODO 5.库存锁定，只要有异常就回滚订单数据,订单号，所有订单项（skuId，skuName，num）
                Boolean isLockSucess = lockStocks(orderCreateTO);
                if(isLockSucess){
                    orderSubmitResponseVO.setOrderEntity(orderCreateTO.getOrderEntity());//锁成功
                    orderSubmitResponseVO.setCode(0);
                    //TODO 6.远程扣减积分
//                    int x = 10/0;

                    //7.订单创建成功发送消息给MQ，超过某个时间后如果该订单仍未支付则取消该订单
                    rabbitTemplate.convertAndSend(MyOrderMQConfig.ORDER_EVENT_EXCHANGE,
                            MyOrderMQConfig.ORDER_DELAY_ROUTE,
                            orderCreateTO.getOrderEntity());


                    return orderSubmitResponseVO;
                }else{
                    orderSubmitResponseVO.setCode(3);//库存锁定失败
                    return orderSubmitResponseVO;
                }

            }else{
                orderSubmitResponseVO.setCode(2);//金额对比失败的状态码为2
                return orderSubmitResponseVO;
            }
        }else {
            orderSubmitResponseVO.setCode(1); //验证失败
            return orderSubmitResponseVO;
        }

//        String preToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + xxlUser.getUserid());
//        if(StringUtils.equals(orderToken,preToken)){
//            //令牌验证通过
//
//        }else{
//            //令牌验证不通过
//            orderSubmitResponseVO.setCode(1);
//        }

    }


    /**
     * 关闭订单方法
     * @param orderEntity
     */
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //查询当前订单的状态是什么
        OrderEntity order = this.getById(orderEntity.getId());
        //如果30分钟后消息过期时仍是新建状态，则将该订单关闭
        if(order!=null && order.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            //关单
            OrderEntity updataOrder = new OrderEntity();//只传入需要改变的属性以及id
            updataOrder.setId(order.getId());
            updataOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updataOrder);
            //发送消息给库存解锁队列
            OrderTO orderTO = new OrderTO();
            BeanUtils.copyProperties(order,orderTO);
            log.error("订单关闭成功，发送库存解锁消息给库存解锁队列！");
            rabbitTemplate.convertAndSend(MyOrderMQConfig.ORDER_EVENT_EXCHANGE,
                    "order.release.other",
                    orderTO);
        }
    }

    /**
     * 获取支付返回结果
     * @param orderSn
     * @return
     */
    @Override
    public PayVO getOrderPay(String orderSn) {
        if(StringUtils.isEmpty(orderSn)){
            log.warn("订单号不能为空！");
            return null;
        }
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        if(orderEntity==null){
            log.warn("查询不到订单信息，检查订单号是否错误！");
            return null;
        }
        if(orderEntity.getStatus()!=0){
            String error = "";
            switch (orderEntity.getStatus()){
                case 1:
                    error = "订单已支付，等待发货，请不要重复支付！";
                    break;
                case 2:
                    error = "订单已发货，请不要重复支付！";
                    break;
                case 3:
                    error = "订单已完成交易，请不要重复支付！";
                    break;
                case 4:
                    error = "订单已关闭，不能支付！";
                    break;
                case 5:
                    error = "该订单属于无效订单！";
                    break;
                default:
                    error = "订单状态异常！";
                    break;

            }
            log.error(error);
            return null;
        }

        PayVO payVO = new PayVO();
        BigDecimal payAmount = orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVO.setTotal_amount(payAmount.toString());
        payVO.setOut_trade_no(orderEntity.getOrderSn());

        //获取订单项信息
        List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        if(itemEntities!=null&&itemEntities.size()!=0){
            OrderItemEntity itemEntity = itemEntities.get(0);
            payVO.setBody(itemEntity.getSkuAttrsVals());

            payVO.setSubject(itemEntity.getSkuName());
        }


        return payVO;
    }

    /**
     * 查询当前用户的订单以及订单详情数据
     * @param params
     * @param userid
     * @return
     */
    @Override
    public PageUtils listWithItem(Map<String, Object> params, String userid) {

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",userid).orderByDesc("create_time")
        );

        for (OrderEntity orderEntity : page.getRecords()) {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderEntity.getOrderSn()));
            orderEntity.setItemEntities(orderItemEntities);
        }
        return new PageUtils(page);
    }

    /**
     * 处理支付宝异步通知
     * @param payAsyncVO
     * @return
     */
    @Override
    public String handlePayResult(PayAsyncVO payAsyncVO) {
        int count = paymentInfoService.count(
                new QueryWrapper<PaymentInfoEntity>()
                        .eq("order_sn", payAsyncVO.getOut_trade_no()).or()
                        .eq("alipay_trade_no", payAsyncVO.getTrade_no()));
        if(count>0){
            log.warn("该订单已经支付，检查是否重复调用，或者回复给支付宝的success信息丢失！");
            return "success";
        }

        //1.保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(payAsyncVO.getTrade_no());
        paymentInfoEntity.setOrderSn(payAsyncVO.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(payAsyncVO.getTrade_status());
        paymentInfoEntity.setCallbackTime(payAsyncVO.getNotify_time());
        paymentInfoEntity.setTotalAmount(payAsyncVO.getTotal_amount());
        paymentInfoEntity.setCallbackContent(payAsyncVO.getSubject());
        paymentInfoEntity.setConfirmTime(new Date());
        //流水信息
        paymentInfoService.save(paymentInfoEntity);

        //2.修改订单状态信息
        if(payAsyncVO.getTrade_status().equals("TRADE_SUCCESS")
                ||payAsyncVO.getTrade_status().equals("TRADE_FINISHED")){
            //支付成功状态
            String order_sn = payAsyncVO.getOut_trade_no();

            /**
             * 修改订单状态为支付状态
             */
            Integer updateCount = baseMapper.updateOrderStatus(order_sn, OrderStatusEnum.PAYED.getCode());
            if(updateCount<=0){
                log.warn("修改订单状态失败，没有任何订单状态被修改！");
            }
        }
        return "success";
    }

    /**
     * 创建秒杀订单
     * @param seckillOrderTO
     */
    @Override
    public Boolean createSeckillOrder(SeckillOrderTO seckillOrderTO) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTO.getOrderSn());
        orderEntity.setMemberId(Long.valueOf(seckillOrderTO.getMemberId()));
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());//新建状态
        BigDecimal payAmount = seckillOrderTO.getSeckillPrice().multiply(new BigDecimal(seckillOrderTO.getNum()));
        orderEntity.setPayAmount(payAmount);
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());

        boolean save = this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTO.getOrderSn());
        orderItemEntity.setSpuId(seckillOrderTO.getSkuId());
        orderItemEntity.setSkuQuantity(seckillOrderTO.getNum());
        orderItemEntity.setRealAmount(payAmount);
        //TODO 获取sku详细信息设置到订单项中
        R r = productFeignService.infoAndAttr(seckillOrderTO.getSkuId());
        if(r.getCode()!=0){
            orderItemService.save(orderItemEntity);
            return true;
        }
        SkuInfoAndAttrsTO skuInfo = r.getData("skuInfo",new TypeReference<SkuInfoAndAttrsTO>() {
        });
        if(skuInfo==null){
            orderItemService.save(orderItemEntity);

            return true;
        }

        orderItemEntity.setSkuName(skuInfo.getSkuName());
        orderItemEntity.setSkuPic(skuInfo.getSkuDefaultImg());
        orderItemEntity.setSkuPrice(skuInfo.getPrice());
        String skuAttrsStr = String.join(";", skuInfo.getSaleAttrNameValues());
        orderItemEntity.setSkuAttrsVals(skuAttrsStr);


        orderItemService.save(orderItemEntity);

        return true;
    }

    /**
     * 修改订单状态为支付状态
     * @param order_sn
     * @param payed
     */


    /**
     * 发送远程请求为所有订单锁库存
     * 库存锁定，只要有异常就回滚订单数据,订单号，所有订单项（skuId，skuName，num）
     * @param orderCreateTO
     */
    private Boolean lockStocks(OrderCreateTO orderCreateTO) {
        WareSkuLockTO wareSkuLockTO = new WareSkuLockTO();
        wareSkuLockTO.setOrderSn(orderCreateTO.getOrderEntity().getOrderSn());
        List<OrderItemVO> orderItemVOS = orderCreateTO.getOrderItems().stream().map(orderItem -> {
            OrderItemVO itemVO = new OrderItemVO();
            itemVO.setCount(orderItem.getSkuQuantity());
            itemVO.setSkuId(orderItem.getSkuId());
            return itemVO;
        }).collect(Collectors.toList());
        wareSkuLockTO.setLocks(orderItemVOS);
        R r = wareFeignService.orderLockStock(wareSkuLockTO);
        if(r.getCode()==0){
            //成功锁库存
            return true;
        }else{
            //锁库存操作失败
            log.warn(r.getCode()+":"+r.getMsg());
            return false;
        }
    }

    //保存订单数据
    private boolean saveOrder(OrderCreateTO orderTO) {
        OrderEntity orderEntity =orderTO.getOrderEntity();
        orderEntity.setCreateTime(new Date());
        boolean isOrderSaveSuccess = this.save(orderEntity);
        if(!isOrderSaveSuccess){
            log.error("订单保存失败，请查看具体错误！");
            return false;
        }

        List<OrderItemEntity> orderItems = orderTO.getOrderItems();
        boolean isOrderItemsSaveSuccess = orderItemService.saveBatch(orderItems);
        if(!isOrderItemsSaveSuccess){
            log.error("订单项保存失败，请查看具体错误！");
            return false;
        }
        return true;



    }

    /**
     * 下单
     *  创建订单、验证token令牌、验证价格、锁库存
     * @param submitVO
     * @return
     */
    private OrderCreateTO createOrder(OrderSubmitVO submitVO,Long memberId){
        OrderCreateTO orderCreateTO = new OrderCreateTO();
        //1. 生成订单id
        String orderSn = IdWorker.getTimeId();

        //2. 生成订单实体类
        OrderEntity orderEntity = buildOrder(submitVO.getAddrId(), orderSn,memberId);
        orderCreateTO.setOrderEntity(orderEntity);

        //3. 获取所有的订单项信息
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        orderCreateTO.setOrderItems(itemEntities);

        //3. 验价,计算价格,积分相关信息
        computePrice(orderEntity,itemEntities);

        return orderCreateTO;
    }

    /**
     * 3. 验价,计算价格相关
     * @param orderEntity
     * @param itemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        //1.订单价格相关
        BigDecimal totalPrice = new BigDecimal("0.0");

        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");


        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;
        for (OrderItemEntity itemEntity : itemEntities) {
            totalPrice = totalPrice.add(itemEntity.getRealAmount());

            coupon = coupon.add(itemEntity.getCouponAmount());
            promotion = promotion.add(itemEntity.getPromotionAmount());
            integration = integration.add(itemEntity.getIntegrationAmount());

            //积分信息和成长值信息
            integrationTotal += itemEntity.getGiftIntegration();
            growthTotal += itemEntity.getGiftGrowth();
        }
        //设置应付总额(总额+运费)
        orderEntity.setTotalAmount(totalPrice);
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));

        orderEntity.setPromotionAmount(integration);
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //删除状态设为0
        orderEntity.setDeleteStatus(0);



    }

    /**
     * 构建所有订单项信息
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        List<CartItemVO> cartItemVOS = cartFeignService.currentUserCartItems();
        if(cartItemVOS==null||cartItemVOS.size()==0){
            log.warn("远程请求——获取的订单项信息为空");
            return null;
        }
        List<Long> skuIds = cartItemVOS.stream().map(CartItemVO::getSkuId).collect(Collectors.toList());
        R r = productFeignService.listSpuInfoBySkuIds(skuIds);
        if(r.getCode()!=0){
            log.warn("远程请求——根据skuIds获取spu信息失败");
            return null;
        }
        Map<Long, SpuInfoTO> data = r.getData(new TypeReference<Map<Long, SpuInfoTO>>() {
        });
        if(data==null || data.size()==0){
            log.warn("根据skuIds获取的spu信息为空");
            return null;
        }
        List<OrderItemEntity> itemEntities = cartItemVOS.stream().map(cartItemVO -> {
            OrderItemEntity orderItemEntity = new OrderItemEntity();
            //1.订单号
            orderItemEntity.setOrderSn(orderSn);

            //2.商品spu信息
            SpuInfoTO spuInfoTO = data.get(cartItemVO.getSkuId());
            orderItemEntity.setSpuId(spuInfoTO.getId());
            orderItemEntity.setSpuBrand(spuInfoTO.getBrandId().toString());
            orderItemEntity.setSpuName(spuInfoTO.getSpuName());
            orderItemEntity.setCategoryId(spuInfoTO.getCatalogId());

            //3.商品的sku信息
            orderItemEntity.setSkuId(cartItemVO.getSkuId());
            orderItemEntity.setSkuName(cartItemVO.getTitle());
            orderItemEntity.setSkuPic(cartItemVO.getImageUrl());
            orderItemEntity.setSkuPrice(cartItemVO.getPrice());
            String skuAttrsStr = StringUtils.join(cartItemVO.getSkuAttr(), ";");
            orderItemEntity.setSkuAttrsVals(skuAttrsStr);
            orderItemEntity.setSkuQuantity(cartItemVO.getCount());

            //4.优惠信息（未实现）

            //5.积分信息（未仔细实现，直接积分等于价格）
            orderItemEntity.setGiftGrowth(cartItemVO.getPrice().multiply(new BigDecimal(cartItemVO.getCount())).intValue());
            orderItemEntity.setGiftIntegration(cartItemVO.getPrice().multiply(new BigDecimal(cartItemVO.getCount())).intValue());

            //6.订单项的价格信息
            orderItemEntity.setPromotionAmount(new BigDecimal("0"));
            orderItemEntity.setCouponAmount(new BigDecimal("0"));
            orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
            //6.1订单项的实际金额
            BigDecimal orign = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
            orign = orign.subtract(orderItemEntity.getPromotionAmount())
                    .subtract(orderItemEntity.getCouponAmount())
                    .subtract(orderItemEntity.getIntegrationAmount());
            orderItemEntity.setRealAmount(orign);

            return orderItemEntity;
        }).collect(Collectors.toList());
        return itemEntities;
    }

    /**
     * 构建订单信息
     * @param addrId
     * @param orderSn
     * @return
     */
    private OrderEntity buildOrder(Long addrId, String orderSn,Long memberId) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberId);

        //1.获取运费信息
        R fareResp = wareFeignService.getFare(addrId);
        if(fareResp.getCode()==0){
            BigDecimal fare = new BigDecimal(fareResp.get("fare").toString()) ;
            orderEntity.setFreightAmount(fare);
        }
        //2.获取收货地址信息
        R addressResp = memberFeignService.info(addrId);
        if(addressResp.getCode()==0){
            MemberReceiveAddressVO address = addressResp.getData("memberReceiveAddress", new TypeReference<MemberReceiveAddressVO>() {
            });
            //设置收货人信息
            orderEntity.setReceiverCity(address.getCity());
            orderEntity.setReceiverDetailAddress(address.getDetailAddress());
            orderEntity.setReceiverName(address.getName());
            orderEntity.setReceiverPhone(address.getPhone());
            orderEntity.setReceiverPostCode(address.getPostCode());
            orderEntity.setReceiverProvince(address.getProvince());
            orderEntity.setReceiverRegion(address.getRegion());

            //订单状态设为新增状态
            orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
            orderEntity.setAutoConfirmDay(7);//自动收货时间为七天

        }
        return orderEntity;
    }

}